<template>
    <view>
        <view class="form-group">
            <view class="title">
                <text v-if="must" class="text-red">*</text>
                {{ title }}
                <text v-if="isShowSize" class="text-gray" style="font-size: 24rpx; font-weight: normal">(每张不超过{{ imgUploadSize }}M)</text>
            </view>
            <view class="action" v-if="isShowSize && imgMax > 1">{{ imgListClone.length }}/{{ imgMax }}</view>
        </view>
        <view class="form-group padding">
            <view class="upload-img">
                <view class="bg-img" @tap="bindPreviewImgTap" :data-url="imgListClone[index]" v-for="(item, index) in imgListClone" :key="index">
                    <image :src="imgListClone[index]" mode="aspectFill"></image>

                    <view class="tag bg-red" @tap.stop.prevent="catchDelImgTap" :data-index="index">
                        <text class="icon-close"></text>
                    </view>

                    <view v-if="isShowNo" class="bg-olive img-no">
                        <text>#{{ index }}</text>
                    </view>
                </view>
                <view class="solid" @tap="bindChooseImgTap" v-if="imgListClone.length < imgMax">
                    <text class="icon-cameraadd"></text>
                </view>
            </view>
        </view>
    </view>
</template>

<script>
const pageHelper = require('@/utils/helper/page_helper.js');
const contentCheckHelper = require('@/utils/helper/content_check_helper.js');
const setting = require('@/utils/setting/setting.js');
const api = require('@/api/api.js');
const utils = require('@/utils/utils.js');
export default {
    data() {
        return {
            imgListClone: []
        };
    },
    options: {
        addGlobalClass: true
    },
    /**
     * 组件的属性列表
     */
    props: {
        imgList: {
            type: Array,
            default: () => []
        },
        imgMax: {
            type: Number,
            default: 4
        },
        title: {
            type: String,
            default: '图片上传'
        },
        must: {
            //是否必填
            type: Boolean,
            default: true
        },
        isCheck: {
            //是否做图片内容校验
            type: Boolean,
            default: true
        },
        isShowNo: {
            //是否显示序号
            type: Boolean,
            default: false
        },
        imgUploadSize: {
            //图片最大大小
            type: Number,
            default: setting.IMG_UPLOAD_SIZE
        },
        isShowSize: {
            //是否提示图片尺寸
            type: Boolean,
            default: true
        }
    },
    mounted() {
        // 处理小程序 attached 生命周期
        this.attached();
        // 处理小程序 ready 生命周期
        this.$nextTick(() => this.ready());
    },
    destroyed: function () {
        // 在组件实例被从页面节点树移除时执行
    },
    /**
     * 组件的方法列表
     */
    methods: {
        ready: function () {},
        attached: function () {},

        /**
         * 选择上传图片
         */
        bindChooseImgTap: function (e) {
            uni.chooseImage({
                count: this.imgMax - this.imgListClone.length,
                //默认9
                mediaType: ['image'],
                sizeType: ['compressed'],
                //可以指定是原图还是压缩图，默认二者都有
                sourceType: ['album', 'camera'],
                //从相册选择
                success: async (res) => {
                    uni.showLoading({
                        title: '上传中...'
                    });
                    
                    let validUrls = [];
                    let hasError = false;
                    
                    for (let k = 0; k < res.tempFiles.length; k++) {
                        let size = res.tempFiles[k].size;
                        let path = res.tempFiles[k].name;
                        
                        // 检查图片格式
                        if (!contentCheckHelper.imgTypeCheck(path)) {
                            hasError = true;
                            pageHelper.showNoneToast('只能上传png、jpg、jpeg格式', 3000);
                            continue;
                        }
                        
                        // 检查图片大小
                        let imageMaxSize = 1024000 * this.imgUploadSize;
                        if (!contentCheckHelper.imgSizeCheck(size, imageMaxSize)) {
                            hasError = true;
                            pageHelper.showNoneToast('单张图片大小不能超过 ' + this.imgUploadSize + 'M', 3000);
                            continue;
                        }
                        let file = res.tempFiles[k];    
                        try {
                            let uploadRes = await new Promise((resolve, reject) => {
                                this.$util.uploadFile(file.path, (res) => {
                                    resolve(res);
                                }, (error) => {
                                    reject(error);
                                });
                            });
                            
                            // console.log('uploadRes=' + JSON.stringify(uploadRes));
                            let url = uploadRes.data.fileUrl;
                            if (url) {
                                validUrls.push(url);
                            }
                        } catch (error) {
                            hasError = true;
                            pageHelper.showNoneToast('上传失败', 3000);
                            console.error('文件上传失败:', error);
                        }
                        console.log('当前validUrls:', validUrls)
                    }
                    
                    // 处理验证通过的图片
                    if (validUrls.length > 0) {
                        // 使用 imgListClone 而不是 imgList，确保删除操作后的状态正确
                        let newImgList = [...this.imgListClone, ...validUrls];
                        this.imgListClone = newImgList;
                        console.log('newImgList=' + JSON.stringify(newImgList));
                        // 发射新的图片数组给父组件
                        this.$emit('upload', {
                            detail: newImgList
                        });
                    }
                    
                    // 隐藏加载提示
                    uni.hideLoading();
                }
            });
        },

        bindPreviewImgTap: function (e) {
            uni.previewImage({
                urls: this.imgListClone,
                current: e.currentTarget.dataset.url
            });
        },

        /**
         * 	删除图片
         */
        catchDelImgTap: function (e) {
            let that = this;
            let callback = function () {
                // 创建新的图片数组，移除指定索引的图片
                // 使用 imgListClone 确保状态一致性
                let newImgList = [...that.imgListClone];
                newImgList.splice(e.currentTarget.dataset.index, 1);
                that.imgListClone = newImgList;
                // 发射新的图片数组给父组件
                that.$emit('upload', {
                    detail: newImgList
                });
            };
            pageHelper.showConfirm('确定要删除该图片吗？', callback);
        }
    },
    created: function () {},
    watch: {
        imgList: {
            handler: function (newVal, oldVal) {
                this.imgListClone = newVal;
            },

            immediate: true,
            deep: true
        }
    }
};
</script>
<style>
@import '../../../style/base/comm.css';
@import '../../../style/public/project.css';

.form-group .upload-img .img-no {
    position: absolute;
    right: 0;
    bottom: 0;
    border-top-left-radius: 6rpx;
    padding: 6rpx 12rpx;
    height: 35rpx;
    opacity: 0.9;
}
</style>
